/*
 * Copyright (C) 2011, 2012 Moravská zemská knihovna v Brně / Moravian Library in Brno
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package cz.mzk.oai.provider.response;

import cz.mzk.oai.provider.OaiException;
import cz.mzk.oai.provider.tools.ArgumentsChecker;
import java.io.IOException;
import java.util.Map;
import java.util.logging.Logger;
import org.dom4j.Document;
import org.dom4j.Element;

/**
 *
 * @author Martin Řehánek (rehan at mzk.cz)
 */
public abstract class OaiVerbResponse extends OaiResponse {

    private static final Logger logger = Logger.getLogger(OaiErrorResponse.class.getName());
    protected Element rootEl;

    public OaiVerbResponse(String verbStr, Map<String, String[]> parameters, String baseUrl) throws IOException {
        super(verbStr, parameters, baseUrl);
    }

    public Document build() throws OaiException, IOException {
        checkParameters();
        logger.fine("parameters checked");
        buildVerbHeader();
        logger.fine("header built");
        createResponse();
        logger.fine("response built");
        return doc;
    }

    //abstract String[] getParametersAllowed();
    abstract String[] getRequiredArguments();

    abstract String[] getOptionalArguments();

    abstract String getExclusiveArgument();

    private void checkParameters() throws OaiException {
        String[] requiredArguments = getRequiredArguments();
        String[] optionalArguments = getOptionalArguments();
        String exclusiveArgument = getExclusiveArgument();
        ArgumentsChecker checker = new ArgumentsChecker(arguments, requiredArguments, optionalArguments, exclusiveArgument);
        checker.run();
    }

    String getArgumentValueIfPresent(String parameter) {
        String[] values = arguments.get(parameter);
        if (values != null) {
            return values[0];
        } else {
            return null;
        }
    }

    abstract void createResponse() throws OaiException, IOException;

    private void buildVerbHeader() throws IOException {
        buildOaiHeader();
        rootEl = doc.getRootElement().addElement(verbStr);
    }
}
